package cn.ctyun.datax.plugin.reader.httpreader.constant;

import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author cuijianpeng
 * @date 2020/5/21 8:56
 */
public enum HttpMethodEnum implements UrlRequest {

    /***/
    GET{
        RestTemplate restTemplate = new RestTemplate();
        @Override
        public String urlRequest(Configuration config) {
            String header = config.getString(KeyConstant.HEADER);
            String url = config.getString(KeyConstant.URL);
            HttpHeaders headers = new HttpHeaders();
            if(StringUtils.isNotBlank(header)){
                JSON.parseObject(header).forEach((k,v)->headers.add(k,v.toString()));
            }
            HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
            LOG.debug(String.format("url:%s,httpMethod:%s,header:%s", config.getString(KeyConstant.URL), "GET", header));
            ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            return resEntity.getBody();
        }
    },
    POST{
        RestTemplate restTemplate = new RestTemplate();
        @Override
        public String urlRequest(Configuration config) {
            String url = config.getString(KeyConstant.URL);
            return restTemplate.postForObject(url, null, String.class);
        }
    }

}
interface UrlRequest {

    static final Logger LOG = LoggerFactory.getLogger(UrlRequest.class);

    public String urlRequest(Configuration config);
}
